package com.lagou.controller;

import com.lagou.feign.CodeServiceFeignClient;
import com.lagou.pojo.Token;
import com.lagou.service.TokenService;
import com.lagou.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;

    /**
     * 注册接口
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code){
        Token oneByEmail = tokenService.findOneByEmail(email);
        if (oneByEmail != null)
            return 1;

        Integer resultCode = codeServiceFeignClient.validateCode(email, code);
        if(resultCode != 0)
            return resultCode;
        Token token = new Token();
        token.setEmail(email);
        token.setToken("");
        try {
            tokenService.save(token);
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
        return resultCode;
    }

    /**
     * 登录接⼝
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password,
                        HttpServletRequest request, HttpServletResponse response){
        Token token = tokenService.findOneByEmail(email);
        if(token == null)
            return "false";
        String tokenStr = UUIDUtil.create();
        token.setToken(tokenStr);
        tokenService.save(token);

        Cookie cookie  = new Cookie("token", tokenStr);
        cookie.setMaxAge(-1);
        cookie.setDomain("test.com");
        cookie.setPath("/");
        response.addCookie(cookie);

        return email;
    }

    /**
     * 根据token查询⽤户登录邮箱
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String getInfo(@PathVariable("token") String token){
        Token tokenEntity = new Token();
        tokenEntity.setToken(token);
        Example<Token> example = Example.of(tokenEntity);
        Optional<Token> one = tokenService.findOneByExample(example);
        return one.isPresent()?one.get().getEmail():"no email";
    }

}
